(function($){
    window.Monk = {
        //字段验证方法
        validateField: function(input_dom, n) {
            var validate_key = input_dom.attr("data-validate"),
            validate_msg = input_dom.attr("data-validate-msg"),
            validate_value = input_dom.val(),
            flag = true,
            single_msg = "";
            if (!validate_key) return flag;
            validate_key = validate_key.split(";"),
            validate_msg !== undefined && (validate_msg = validate_msg.split(";")),
            $.each(validate_key, function(validate_key, single_key) {
                var single_key = $.trim(single_key).split(":"),
                single_key_name = single_key[0],
                single_key_value = single_key.length > 1 ? single_key[1] : null,
                validate_result = null;
                if (single_key_name == "userdefined") {
                    var new_validate = $.Event("validate");
                    input_dom.trigger(new_validate, [validate_value, single_key_value]),
                    validate_result = new_validate.result || {
                        valid: true
                    }
                } else validate_result = Monk.validate[single_key_name](validate_value, single_key_value);
                if (!validate_result.valid) return flag = validate_result.valid,
                validate_msg && validate_msg.length && validate_msg[validate_key] ? single_msg = validate_msg[validate_key] : validate_result.errorMsg ? single_msg = validate_result.errorMsg: single_msg = "",
                single_key_name == "required" && n && (flag = true, single_msg = ""),
                false
            });
            if (!flag) {
                input_dom.addClass("error").nextAll(".desc").hide();
                if (single_msg) {
                    var a = input_dom.nextAll(".error");
                    a.length || (a = $("<p class='error'></p>").insertAfter(input_dom)),
                    a.text(single_msg).show()
                }
            } else input_dom.removeClass("error").nextAll(".desc").show().end().nextAll(".error").remove();
            return flag;
        },
		//验证器
        validate: {
            required: function(e, n) {
                return {
                    valid: !!$.trim(e),
                    errorMsg: "请填写这个字段"
                }
            },
            length: function(e, t) {
                t = (t || "0").split(",");
                var n = e.length,
                r = t[0] * 1,
                i = t.length > 1 ? t[1] * 1: null;
                return {
                    valid: !e || n >= r && (!i || n <= i),
                    errorMsg: "这个字段的长度不能" + (r > 0 ? "少于" + r + "位": "") + (i ? "多余" + i + "位": "")
                }
            },
            range: function(e, t) {
                t = (t || "0").split(",");
                var n = t[0] * 1,
                r = t.length > 1 ? t[1] * 1: null;
                return {
                    valid: !e || e >= n && (!r || e <= r),
                    errorMsg: "这个字段的值" + (n > 0 ? "不能小于" + n: "") + (r ? "不能大余" + r: "")
                }
            },
            email: function(e, t) {
                var n = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
                return {
                    valid: !e || n.test(e),
                    errorMsg: "请填写正确的邮箱地址"
                }
            },
            number: function(e, t) {
                return {
                    valid: !e || /^\d+$/.test(e),
                    errorMsg: "请填写数字"
                }
            },
            mobile: function(e, t) {
                return {
                    valid: !e || /^\d{11}$/.test(e),
                    errorMsg: "请填写一个有效的手机号码"
                }
            }
        },
        //路径解析
        parseParams: function(t) {
            if (!t) return null;
            var n = /([^&=]+)=?([^&]*)/g,
            r = /\+/g,
            i = function(e) {
                return decodeURIComponent(e.replace(r, " "))
            };
            params = {},
            e;
            while (e = n.exec(t)) {
                var s = i(e[1]),
                o = i(e[2]);
                s.substring(s.length - 2) === "[]" ? (s = s.substring(0, s.length - 2), (params[s] || (params[s] = [])).push(o)) : params[s] = o
            }
            return params
        },
        //全局加载图标
        globalLoading: function(txt) {
            if (txt == "hide") $("#mask, .global-loading").remove();
            else {
                var mask_div = $("<div id='mask' class='hidden'></div>").appendTo("body"),
                txt_div = $("<div class='global-loading'>" + txt + "</div>").appendTo("body");
                setTimeout(function() {
                    mask_div && mask_div.css({
                        cursor: "default"
                    }).removeClass("hidden"),
                    txt_div && txt_div.css({
                        marginLeft: -txt_div.outerWidth() * .5,
                        marginTop: -txt_div.outerHeight() * .5
                    })
                },
                20)
            }
        },
        //确认框
        confirm: function(e) {
            var confirm_div = $("<div class='message-content'><p></p><div class='dialog-buttons clearfix'><button class='btn btn-primary btn-yes'></button><a href='javascript:void(0)' class='link-no'></a></div></div>");
            confirm_div.find("p").html(e.msg),
            confirm_div.find(".dialog-buttons .btn-yes").text(e.ok || "确定").on("click", 
            function(event) {
                Monk.dialog("hide"),
                e.callback(true)
            }),
            confirm_div.find(".dialog-buttons .link-no").text(e.cancel || "取消").on("click", 
            function(event) {
                event.preventDefault(),
                Monk.dialog("hide"),
                e.callback(false)
            }),
            Monk.dialog($.extend({
                el: confirm_div,
                width: 450
            },
            e))
        },

        //对话框
        dialog: function() {
            if (typeof arguments[0] == "string" && arguments[0] == "hide") return $(document).off(".dialog"),
            $("#mask").remove(),
            $(".dialog").remove();
            if (typeof arguments[0] == "object") {
                var e = $.extend({
                    el: null,
                    width: 600,
                    height: "auto",
                    modal: false,
                    padding: true,
                    closeButton: true
                },
                arguments[0]);
                Monk.dialog("hide");
                var dialog_div = $("<div class='dialog'><div class='dialog-wrapper clearfix'></div><a href='javascript:;' class='link-close-dialog'>Close</a></div>").css({
                    width: e.width,
                    height: e.height
                }).appendTo("#toolbar .content:last");
                e.closeButton || dialog_div.find(".link-close-dialog").remove(),
                dialog_div.find(".dialog-wrapper").append(e.el),
                dialog_div.find(".link-close-dialog").on("click", 
                function(e) {
                    e.preventDefault(),
                    Monk.dialog("hide")
                }),
                $(document).on("keydown.dialog", 
                function(e) {
                    e.which == 27 && Monk.dialog("hide")
                }),
                setTimeout(function() {
                    dialog_div.css({
                        marginLeft: -e.width / 2,
                        marginTop: -dialog_div.height() / 2
                    })
                },
                20);
                if (e.modal) {
                    var r = $("<div id='mask' class='hidden'></div>").appendTo("#toolbar .content:last");
                    r.on("click", 
                    function(e) {
                        Monk.dialog("hide")
                    }),
                    setTimeout(function() {
                        r.removeClass("hidden")
                    },
                    20)
                }
                return dialog_div
            }
            return null
        },
        
        //提示框
        message: function(option) {
            var msg_div = $("<div class='message-content'><p></p><div class='dialog-buttons clearfix'><button class='btn'></button></div></div>");
            msg_div.find("p").html(option.msg),
            msg_div.find(".dialog-buttons button").text(option.ok || "我知道了").on("click", 
            function(e) {
                Monk.dialog("hide")
            }),
            Monk.dialog($.extend({
                el: msg_div,
                width: 450
            },
            option))
        },
    }
})(jQuery);

(function($){
    $("#toolbar .user-avatar").on('click',function(){
        $("#toolbar .user-bar").toggleClass('on');
    })
})(jQuery);

(function($){
    var p_c = $("#toolbar .content");

    function showAdd(){
        $(".user-category-form").show().find('.uc-name').focus();
    };
    function hideAdd(){
        $(".user-category-form").find(".uc-name").val("").removeClass("error").end().hide();
    };
    function doAdd(e){
        e.preventDefault();
        uc_name = $(".user-category-form").find(".uc-name");
        submit_button = $(".user-category-form button[data-disable-with]");
        original_text = submit_button.text();
        r = Monk.validateField(uc_name);
        if(r){
            $.ajax({
                url:$(".user-category-form").find("form").attr('action'),
                dataType: "json",
                data: {uc_name:$(uc_name).val()},
                type: "post",
                beforeSend: function(){
                    submit_button.prop("disabled",true);
                    submit_button.text(submit_button.attr('data-disable-with'));
                },
                success:function(data, textStatus, jqXHR){
                    p_c.trigger("ajax:success", [$(uc_name).val(), original_text, data]);
                },
                error:function(XMLHttpRequest, textStatus, errorThrown){
                    p_c.trigger("ajax:error", [$(uc_name).val(), original_text]);
                },
                complete:function(XMLHttpRequest, textStatus){
                    p_c.trigger("ajax:complete", [XMLHttpRequest, textStatus]);
                }
            });
        }
    };
    function addComplete(e,n,o,d){
        if(d.status == "success"){
            var n_uc = $(".uc-title:first").clone(true);
            n_uc.find("h4").text(n);
            n_uc.insertBefore($(".uc-title:first"));
            $(".user-category-form").find(".uc-name").val("");
            $(".user-category-form button[data-disable-with]").prop("disabled",false);
            $(".user-category-form button[data-disable-with]").text(o);
        }else{
            $(".user-category-form").find(".uc-name").val("");
            $(".user-category-form button[data-disable-with]").prop("disabled",false);
            $(".user-category-form button[data-disable-with]").text(o);
        }
    };

    p_c.on('click','.btn-new-user-category',showAdd).on("click", ".btn-cancel-user-category", hideAdd).on("click",".btn-create-user-category",doAdd).on("validate", ".user-category-form form", 
        function(e, t, n) {
            var r = {
                valid: true
            };
            return t ? t.length > 100 && (r.valid = false, r.errorMsg = "", Monk.message({
                msg: "自定义分类名称最长100个字符"
            })) : (r.valid = false, r.errorMsg = ""),
            r
        }
    ).on('ajax:success', addComplete);
})(jQuery);

(function($){
    var applist = $( "#toolbar .app-list" );
    var apps = $( "#toolbar .apps" );
    $( ".apps", applist ).sortable({
        connectWith: 'ul',
        items: "li",
        cursor: "move",
        helper: "clone",
        tolerance: "pointer",
        placeholder: "#toolbar > app-placeholder",
        containment: "#toolbar .app-list",
        stop: function(event, ui) {
            var i = ui.item,
            s = i.closest(".todos").find(".todo").map(function() {
                return e(this).data("guid")
            }).get(),
            o = i.closest(".todolist").data("guid"),
            u = i.data("guid"),
            a = i.data("project-guid");
            e.ajax({
                url: "/projects/" + a + "/todos/" + u + "/reorder/",
                data: {
                    list_guid: o,
                    guids: s.join(",")
                }
            })
        }
    })
})(jQuery);